package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.louwowo.cache.key.RedisKeys;
import cn.wolfcode.louwowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 做登陆验证的拦截器
 */
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Reference
    private IUserInfoRedisService redisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //判断访问的方法是否需要用户登陆
            if (hm.hasMethodAnnotation(RequireLogin.class)){
                String token = CookieUtil.getToken(request, response);
                UserInfo userInfo = redisService.getUserByToken(token);
                //如果没有登陆，则跳转登陆页面
                if (userInfo == null){
                    response.sendRedirect("/login.html");
                }
            }
        }
        return true;
    }
}
